#from __future__ import absolute_import, print_function

import tweepy
from tweepy import *
import codecs
# == OAuth Authentication ==
#
# This mode of authentication is the new preferred way
# of authenticating with Twitter.

# The consumer keys can be found on your application's Details
# page located at https://dev.twitter.com/apps (under "OAuth settings")
consumer_key="JMp782aclhhKXnXeovkYv7oLb"
consumer_secret="WjQcOdb7EFa2yRqp5dC6hSEflxMdFjiiFskMfQvTIkiRnR58z9"

# The access tokens can be found on your applications's Details
# page located at https://dev.twitter.com/apps (located
# under "Your access token")
access_token="40667134-dxFW8eYBrbovc3PazT9ImdIq1e4Zkp6ARKGHkBN4J"
access_token_secret="cmZbDTB6hic7LVq6q44wrmn5H0OcREX3WTUc0JWzcLdtw"

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.secure = True
auth.set_access_token(access_token, access_token_secret)

api = tweepy.API(auth)

# If the authentication was successful, you should
# see the name of the account print out
print(api.me().name)

# If the application settings are set for "Read and Write" then
# this line should tweet out the message to your account's
# timeline. The "Read and Write" setting is on https://dev.twitter.com/apps
#api.update_status('Updating using OAuth authentication via Tweepy!')

class Files():
    ""
    def __init__(self, filename):
        self.file=codecs.open(filename,'w+','utf-8')

    def getline(self):
        return self.file.readline()

    def writetofile(self, streamdata):
        self.file.write(streamdata)
        self.file.flush()

class StdOutListener(StreamListener):
    """ A listener handles tweets are the received from the stream.
    This is a basic listener that just prints received tweets to stdout.
    """
    def __init__(self, sfile, error_log):
        self.file=sfile
        self.error_log=error_log

    def on_data(self, data):
        self.file.writetofile(data)
        print(data)
        return True

    def on_error(self, status):
        print(status)
        self.error_log.writetofile(str(status))

if __name__ == '__main__':
    streamfile = Files("stream.txt")
    error_log = Files("error.txt")
    l = StdOutListener(streamfile, error_log)


    stream = Stream(auth, l)
    stream.filter(track=['basketball'],languages=['en'])
    #stream.disconnect()